package jgl.vajra.kingkong.part.vehicle.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.AddressBean;
import jgl.vajra.kingkong.bean.CityChoiceBean;
import jgl.vajra.kingkong.bean.NearbyPointsBean;
import jgl.vajra.kingkong.bean.PeripheralPoiBean;
import jgl.vajra.kingkong.bean.WorkplaceBean;
import jgl.vajra.kingkong.databinding.ActivityWorkingFieldBinding;
import jgl.vajra.kingkong.event.WorkingFieldEvent;
import jgl.vajra.kingkong.event.WorkplaceEvent;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.part.vehicle.contract.WorkingFieldContract;
import jgl.vajra.kingkong.part.vehicle.viewModel.WorkingFieldViewModel;
import jgl.vajra.kingkong.utils.RandomUtils;
import jgl.vajra.kingkong.widget.giide.GlideImageLoader;
import jgl.vajra.kingkong.widget.manager.SPManager;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.permissions.PermissionListener;
import jgl.vajra.kingkong.widget.permissions.PermissionsUtil;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.view.RatingBar;

/**
 * 干活地
 */
@CreateViewModel(WorkingFieldViewModel.class)
public class WorkingFieldActivity extends BaseMVVMActivity<WorkingFieldViewModel, ActivityWorkingFieldBinding> implements WorkingFieldContract.View {
    private BaiduMap mBaiduMap;
    private MapStatus mapBuild;
    private PeripheralPoiBean data;
    private int type;
//    private AddressBean addressData;
    private String typeModel;
    private List<NearbyPointsBean> dataPoints;
    private CityChoiceBean selectLocationData;

    @Override
    public int getLayoutId() {
        return R.layout.activity_working_field;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);
        type = getIntent().getIntExtra("type", -1);
        typeModel = getIntent().getStringExtra("typeModel");

        //位置信息
        //addressData = SPManager.HomeData.getAddressData();
        selectLocationData = SPManager.HomeData.getSelectLocationData();

        mBinding.toolbar.setNavigationIcon(R.drawable.ic_left_arrow_white_bg);
        mBinding.toolbar.setNavigationOnClickListener(view -> finish());
        //禁止百度地图的手势
      /*  UiSettings settings = mBinding.mapView.getMap().getUiSettings();
        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setZoomGesturesEnabled(false);//获取是否允许缩放手势返回:是否允许缩放手势
        */
        mBinding.mapView.showScaleControl(false);  // 设置比例尺是否可见（true 可见/false不可见）
        mBinding.mapView.showZoomControls(false);  // 设置缩放控件是否可见（true 可见/false不可见）
        View child = mBinding.mapView.getChildAt(1); // 找到百度LOGO控件对象
        if ((child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);  // 设置child这个控件是否可见（VISIBLE 可见/INVISIBLE不可见 /GONE 完全隐藏）
        }

        mBaiduMap = mBinding.mapView.getMap();
        //开启热力图
        mBaiduMap.setBaiduHeatMapEnabled(false);

        setMapViewAddress(Double.parseDouble(selectLocationData.latitude), Double.parseDouble(selectLocationData.longitude));

        //点击Marker
        /*mBaiduMap.setOnMarkerClickListener(marker -> {
            String id = marker.getId();
            int position = Integer.parseInt(marker.getTitle());
            String avatar = dataPoints.get(position).avatar;
            String depreciation = dataPoints.get(position).depreciation;
            String carPicture = dataPoints.get(position).carPicture;
            String remark = dataPoints.get(position).remark;
            String address = dataPoints.get(position).address;
            String name = dataPoints.get(position).name;
            String scoreLevel = dataPoints.get(position).scoreLevel;
            String exponent = dataPoints.get(position).exponent;
            String invitation = dataPoints.get(position).invitation;

            View view = View.inflate(WorkingFieldActivity.this, R.layout.view_working_field, null);
            ImageView ivAvatar = view.findViewById(R.id.iv_avatar);
            ImageView ivCarPicture = view.findViewById(R.id.iv_car_picture);
            TextView tvDepreciation = view.findViewById(R.id.tv_depreciation);
            TextView tvRemark = view.findViewById(R.id.tv_remark);
            TextView tvAddress = view.findViewById(R.id.tv_address);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvScoreLevel = view.findViewById(R.id.tv_score_level);
            RatingBar star = view.findViewById(R.id.star);
            TextView tvExponent = view.findViewById(R.id.tv_exponent);

            GlideImageLoader.onAvatarDisplayRound(ivAvatar, avatar, null);
            GlideImageLoader.onDisplayRadius(ivCarPicture, carPicture, R.dimen.dp_5);
            if (TextUtils.isEmpty(depreciation)) {
                tvDepreciation.setVisibility(View.GONE);
            } else {
                tvDepreciation.setVisibility(View.VISIBLE);
                tvDepreciation.setText(depreciation);
            }
            tvRemark.setText(remark);
            tvAddress.setText(address);
            tvName.setText("机佬:" + name);
            tvScoreLevel.setText(scoreLevel);
            star.setStar(Float.parseFloat(scoreLevel));

            if (TextUtils.isEmpty(exponent)) {
                tvExponent.setVisibility(View.GONE);
            } else {
                tvExponent.setVisibility(View.VISIBLE);
                tvExponent.setText(exponent);
            }

            //构造InfoWindow
            //-100 InfoWindow相对于point在y轴的偏移量
            InfoWindow mInfoWindow = new InfoWindow(view, marker.getPosition(), -150);
            //使InfoWindow生效
            mBaiduMap.showInfoWindow(mInfoWindow);
            ImageView ivClose = view.findViewById(R.id.iv_close);
            ivClose.setOnClickListener(v -> {
                //关闭InfoWindow
                mBaiduMap.hideInfoWindow();
            });

            TextView llItem = view.findViewById(R.id.ll_item);
            llItem.setOnClickListener(v -> {
                IntentManager.toOwnerDetailsActivity(this, invitation);
            });

            return false;
        });*/


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            //地图状态开始改变。
            public void onMapStatusChangeStart(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            //地图状态改变结束
            public void onMapStatusChangeFinish(MapStatus status) {
                //改变结束之后，获取地图可视范围的中心点坐标
                LatLng latLng = status.target;
                //拿到经纬度之后，就可以反地理编码获取地址信息了
                GeoCoder geocoder = GeoCoder.newInstance();
                geocoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        String name = "";
                        if (reverseGeoCodeResult.getPoiRegionsInfoList() != null && reverseGeoCodeResult.getPoiRegionsInfoList().size() != 0)
                            name = reverseGeoCodeResult.getPoiRegionsInfoList().get(0).getRegionName();
                        else if (reverseGeoCodeResult.getPoiList() != null && reverseGeoCodeResult.getPoiList().size() != 0)
                            name = reverseGeoCodeResult.getPoiList().get(0).name;

                        if (TextUtils.isEmpty(name)) {
                            ToastUtils.showShort("定位失败，请重试或手动输入地址");
                            return;
                        }
                        String address = String.format("%s%s", reverseGeoCodeResult.getAddressDetail().city, reverseGeoCodeResult.getAddressDetail().district);
                        data = new PeripheralPoiBean(name, address, latLng.latitude, latLng.longitude, reverseGeoCodeResult.getAddressDetail().city);
                        mBinding.tvName.setText(name);
                        mBinding.tvTitle.setText(name);
                        mBinding.tvAddress.setText(address);
                    }
                });

//这个要放在后面！！！！！！！
                LatLng point = new LatLng(latLng.latitude, latLng.longitude);
                geocoder.reverseGeoCode(new ReverseGeoCodeOption().location(point));

                Map<String, Object> map = new HashMap<>();
                map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
                map.put("model", typeModel);
                map.put("longitude", latLng.longitude);
                map.put("latitude", latLng.latitude);

                mViewModel.getNearbyPoints(map);
            }

            //地图状态变化中
            public void onMapStatusChange(MapStatus status) {
            }
        });
    }

    public void addMaker(double longitude, double latitude, int i, String picture) {
        //定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);

        View view = View.inflate(WorkingFieldActivity.this, R.layout.view_item_working_field, null);
        Glide.with(this)
                .load(picture)
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                        ImageView ivIcon = view.findViewById(R.id.iv_icon);
                        ivIcon.setImageDrawable(resource);
                        //构建MarkerOption，用于在地图上添加Marker
                        MarkerOptions options = new MarkerOptions()
                                .position(point)
                                .title(i + "")
                                .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));

                        //在地图上添加Marker，并显示
                        mBaiduMap.addOverlay(options);
                    }
                });
    }

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    @Override
    public void onResume() {
        mBinding.mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mBinding.mapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mBinding.mapView.onDestroy();
        super.onDestroy();
    }

    //回到当前位置
    @Override
    public void onReposition() {
        setMapViewAddress(Double.parseDouble(selectLocationData.latitude), Double.parseDouble(selectLocationData.longitude));
    }

    //通讯录
    @Override
    public void onMailList() {
        String[] permissions = {
                Manifest.permission.READ_CONTACTS,

        };
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        ToastUtils.showShort("请到设置-权限管理中开启");
                    }
                }, permissions, false, null
        );
    }

    // 确定吊货地
    @Override
    public void onDetermine() {
        if (data == null && TextUtils.isEmpty(data.detailedAddress)) {
            ToastUtils.showShort("请查看当前定位");
            return;
        }

        String name = mBinding.etName.getText().toString().trim();
        String phone = mBinding.etPhone.getText().toString().trim();

        WorkplaceBean bean = new WorkplaceBean();
        bean.name = name;
        bean.phone = phone;
        bean.address = data.address;
        bean.city = data.city;
        bean.detailedAddress = data.detailedAddress;
        bean.latitude = data.latitude;
        bean.longitude = data.longitude;
        EventBus.getDefault().post(new WorkplaceEvent(bean, type));
        finish();
    }


    //返回的数据
    @Override
    public void returnNearbyPointsData(List<NearbyPointsBean> data) {
        mBaiduMap.clear();
        dataPoints = data;
        for (int i = 0; i < data.size(); i++) {
            addMaker(Double.parseDouble(data.get(i).longitude), Double.parseDouble(data.get(i).latitude), i, data.get(i).picture);
        }
    }

    //修改地址
    @Override
    public void onModifyAddress() {
        IntentManager.toPeripheralPoiActivity(this);
    }

    //常用地址
    @Override
    public void onCommonAddress() {
        IntentManager.toCommonAddressActivity(this, 111);
    }

    /* * 跳转联系人列表的回调函数 * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = getPhoneContacts(uri);
            mBinding.etName.setText(contacts != null ? contacts[0] : "");
            String phone = contacts != null ? contacts[1] : "";
            if (!TextUtils.isEmpty(phone)) {
                phone = phone.replace(" ", "");
            }
            mBinding.etPhone.setText(phone);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone.close();
            }
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }


    public void setMapViewAddress(double latitude, double longitude) {
        LatLng ll = new LatLng(latitude, longitude);
        mapBuild = new MapStatus.Builder()
                .target(ll)
                .zoom(12f)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWorkingFieldEvent(WorkingFieldEvent event) {
        data = event.data;

        mBinding.tvName.setText(event.data.detailedAddress);
        mBinding.tvTitle.setText(event.data.detailedAddress);
        mBinding.tvAddress.setText(event.data.address);

        setMapViewAddress(event.data.latitude, event.data.longitude);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWorkplaceEvent(WorkplaceEvent event) {
        if (event.type == 111) {
            WorkplaceBean workplaceBean = event.bean;
            data = new PeripheralPoiBean(workplaceBean.detailedAddress, workplaceBean.address, workplaceBean.latitude, workplaceBean.longitude, workplaceBean.city);

            mBinding.tvName.setText(workplaceBean.detailedAddress);
            mBinding.tvTitle.setText(workplaceBean.detailedAddress);

            mBinding.tvAddress.setText(workplaceBean.address);
        }
        setMapViewAddress(event.bean.latitude, event.bean.longitude);
    }

}
